//
//  AddFriendsViewController.m
//  觅影
//
//  Created by  陶虹 on 16/4/9.
//  Copyright © 2016年  陶虹. All rights reserved.
//

#import "MyFriendsViewController.h"
#import "MovieFriendsViewController.h"
#import "FriendsInformViewController.h"
#import "AddFriendsViewController.h"
#import "MyFriendsCell.h"
#import "MyFriendsModel.h"
#import "ChatViewController.h"

@interface MyFriendsViewController ()<UITableViewDelegate, UITableViewDataSource>
@property (strong, nonatomic) IBOutlet UIButton *friendsInformButton;
@property (strong, nonatomic) IBOutlet UIButton *addFriendsButton;
@property (strong, nonatomic) IBOutlet UILabel *numLabel;
@property (strong, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *modelArray;

@property (nonatomic, assign) BOOL isLogin;
@property (nonatomic, strong) NSString *username;
@property (nonatomic, strong) NSString *password;
@property (nonatomic, strong) NSNumber *has_new_friend;
@end

@implementation MyFriendsViewController

- (void)loadView{
    [super loadView];
    
    // 获取好友列表 block异步
    [[EaseMob sharedInstance].chatManager asyncFetchBuddyListWithCompletion:^(NSArray *buddyList, EMError *error) {
        if (!error) {
            NSLog(@"好友列表获取成功 --- %@", buddyList);
            [_modelArray removeAllObjects];
            [_modelArray addObjectsFromArray:buddyList];
            [_tableView reloadData];
        }
    } onQueue:dispatch_get_main_queue()];
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(removeFromSuperview) name:@"remove" object:nil];
    
    [self netRequest];
    [self putUpView];

    
    // 注册环信用户名和密码 应该写在注册登陆界面上
    // 登陆和注册有3种方法：1、同步方法，2、通过delegate回调的方法，3、block异步方法
    // 其中官方推荐使用block异步方法，这里使用blok异步方法
        
    if (_isLogin == YES) {
        // 开始注册
        [[EaseMob sharedInstance].chatManager asyncRegisterNewAccount:_username password:_password withCompletion:^(NSString *username, NSString *password, EMError *error) {
            if (!error) {
                NSLog(@"注册成功");
            }
        } onQueue:dispatch_get_main_queue()];
    }
    
    // 环信签协议
    [[EaseMob sharedInstance].chatManager addDelegate:(id)self delegateQueue:dispatch_get_main_queue()];
    
    // 同意好友申请, 刷新界面通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(addFriend:) name:@"add" object:nil];
    
}
- (void)addFriend:(NSNotification *)notification{
    NSArray *buddyList = notification.object;
    [self.modelArray removeAllObjects];
    [self.modelArray addObjectsFromArray:buddyList];
    [self.tableView reloadData];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"add" object:nil];
}

- (NSMutableArray *)modelArray{
    if (!_modelArray) {
        self.modelArray = [NSMutableArray array];
    }
    return _modelArray;
}

- (void)putUpView{
        
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.rowHeight = 50;
    self.tableView.separatorStyle = UITableViewCellSelectionStyleNone;
    [self.tableView registerNib:[UINib nibWithNibName:@"MyFriendsCell" bundle:nil] forCellReuseIdentifier:@"myFriendsCell"];
    
    self.numLabel.hidden = YES;
}

- (void)netRequest{
    NSString *myID = [[NSUserDefaults standardUserDefaults]objectForKey:@"myid"];
    [RequestManager requestWithUrl:[NSString stringWithFormat:@"http://static.v6v7.com/snowman_api/user/friend_list_sort_by_new_msg?uid=%@",myID] requestType:RequestTypeGET parDic:nil finshed:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        self.has_new_friend = dic[@"result"][@"has_new_friend"];
 
        NSArray *dataArray = dic[@"result"][@"data"];
        for (NSDictionary *dataDic in dataArray) {
            MyFriendsModel *model = [[MyFriendsModel alloc] init];
            [model setValuesForKeysWithDictionary:dataDic];
            [self.modelArray addObject:model];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
            if (self.has_new_friend.integerValue > 0) {
                self.numLabel.hidden = NO;
                self.numLabel.text = [NSString stringWithFormat:@"%@", self.has_new_friend];
            }
        });
    } error:^(NSError *error) {
        NSLog(@"我的好友列表请求数据失败");
    }];
}

#pragma mark --- tabelView代理方法 ---
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.modelArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    MyFriendsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"myFriendsCell" forIndexPath:indexPath];
    MyFriendsModel *model = self.modelArray[indexPath.row];
    [cell configureCellWithModel:model];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    MyFriendsModel *model = self.modelArray[indexPath.row];
    ChatViewController *chatVc = [[ChatViewController alloc] init];
    chatVc.buddy = model;
    chatVc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:chatVc animated:YES];
}


// 好友请求
- (IBAction)friendsInformbuttonAction:(id)sender {
    FriendsInformViewController *infromVc = [[FriendsInformViewController alloc] initWithNibName:@"FriendsInformViewController" bundle:nil];
    infromVc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:infromVc animated:YES];
}

// 添加好友
- (IBAction)addFriendsButtonAction:(id)sender {
    AddFriendsViewController *addVc = [[AddFriendsViewController alloc] initWithNibName:@"AddFriendsViewController" bundle:nil];
    addVc.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:addVc animated:YES];
}


// 实现通知方法
- (void)removeFromSuperview{
    [self removeFromParentViewController];
    [self.view removeFromSuperview];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"remove" object:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
